#!/usr/bin/env bash

# This script runs the provided command in the Docker container corresponding to the currently
# checked-in image id.

readonly SCRIPTS_DIR="$(dirname "$0")"
# shellcheck source=scripts/common
source "$SCRIPTS_DIR/common"

mkdir -p './bazel-cache'
mkdir -p './cargo-cache'

docker_run_flags=(
  '--rm'
  '--tty'
  '--env=TERM=xterm-256color'
  '--env=BAZEL_REMOTE_CACHE_ENABLED'
  '--env=BAZEL_GOOGLE_CREDENTIALS'
  '--env=OAK_KVM_TESTS'
  '--env=RUST_BACKTRACE'
  '--env=RUST_LOGS'
  "--volume=$PWD/bazel-cache:/home/docker/.cache/bazel"
  "--volume=$PWD/cargo-cache:/home/docker/.cargo"
  "--volume=$PWD:/workspace"
  # Enable Docker-in-Docker by giving the container access to the host docker
  # daemon.
  "--volume=$XDG_RUNTIME_DIR/docker.sock:/var/run/docker.sock"
  # The container uses the host docker daemon, so docker commands running in
  # the container actually access the host filesystem. Thus mount the /tmp
  # directory as a volume in the container so that it can access the outputs of
  # docker commands that write to /tmp.
  '--volume=/tmp:/tmp'
  '--volume=/dev/log:/dev/log'
  # Provide readonly access to the kernel image and kernel volumes of the host
  # to enable virt-make-fs which requires access to a kernel.
  '--volume=/boot:/boot:ro'
  '--volume=/lib/modules:/lib/modules:ro'
  '--workdir=/workspace'
  '--network=host'
  '--security-opt=seccomp=unconfined'
)

# If the host supports KVM, allow the docker image to use it.
if [[ -e "/dev/kvm" ]]; then
  readonly HOST_KVM_GID="$(getent group kvm | cut -d: -f3)"
  docker_run_flags+=(
    "--device=/dev/kvm"
    "--env=HOST_KVM_GID=${HOST_KVM_GID}"
  )
fi

# If the host supports virtio vhost vsock, allow the docker image to use it.
if [[ -e "/dev/vhost-vsock" ]]; then
  docker_run_flags+=(
    "--device=/dev/vhost-vsock"
  )
fi

# If the host supports the vsock device, allow the docker image to use it.
if [[ -e "/dev/vsock" ]]; then
  docker_run_flags+=(
    "--device=/dev/vsock"
  )
fi

# Some CI systems (GitHub actions) do not run with an interactive TTY attached.
if [[ -z "${CI:-}" ]]; then
  docker_run_flags+=('--interactive')
fi

# Run the provided command.
docker run "${docker_run_flags[@]}" "$DOCKER_IMAGE_ID" "$@"
